//
//  WTLiveHelper.m
//  WTLiveSDKDemo
//
//  Created by ben on 16/10/9.
//  Copyright © 2016年 ben. All rights reserved.
//

#import "WTLiveHelper.h"
#import <AVFoundation/AVFoundation.h>
#import "WTCategories.h"

@implementation WTLiveHelper

+ (void)requestAccessForAudio:(void (^)(BOOL granted))handler{
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    switch (status) {
        case AVAuthorizationStatusNotDetermined:{
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
                if (!granted) {
                    handler(NO);
                }else {
                    handler(YES);
                }
            }];
            break;
        }
        case AVAuthorizationStatusAuthorized:{
            handler(YES);
            break;
        }
        case AVAuthorizationStatusDenied:
        case AVAuthorizationStatusRestricted:
            handler(NO);
            break;
        default:
            break;
    }
}

+ (void)requestAccessForVideo:(void (^)(BOOL granted))handler {
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (status) {
        case AVAuthorizationStatusNotDetermined:{
            // 许可对话没有出现，发起授权许可
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (!granted) {
                    handler(NO);
                }else {
                    handler(YES);
                }
            }];
            break;
        }
        case AVAuthorizationStatusAuthorized:{
            // 已经开启授权，可继续
            handler(YES);
            break;
        }
        case AVAuthorizationStatusDenied:
        case AVAuthorizationStatusRestricted:
            // 用户明确地拒绝授权，或者相机设备无法访问
            handler(NO);
            break;
        default:
            break;
    }
}

+ (void)requestLiveAccess:(void (^)(BOOL granted))handler{
    
    [[self class] requestAccessForVideo:^(BOOL granted) {
        if(granted){
            [[self class] requestAccessForAudio:^(BOOL granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    handler(granted);
                });
            }];
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(granted);
            });
        }
    }];

}
@end
